<?php

class Quad_Form_Element_OptionsCollection extends Quad_Iterable {
	
	protected $_element;
	protected $_selectedIndex = -1;
	protected $_memberClass = "Quad_Form_Element_Option";
	
	public function __construct(Quad_Form_Element $element, $options=array()) {
		$this->_element = $element;
		$optionObjects = array();
		foreach ($options as $k => $o) {
			if (!($o instanceof $this->_memberClass)) {
				$o = new $this->_memberClass($o, $k);
			}
			$optionObjects[] = $o;
		}
		parent::__construct($optionObjects);
	}
	
	public function __set($p,$v) {
		if ($p == 'selectedIndex') {
			$v = (int) $v;
			if ($v > $this->count() || $v < -1) {
				$v = -1;
			}
			$this->_selectedIndex = $v;
			foreach ($this as $i => $option) {
				$option->selected = ($i == $v);
			}
		}
		elseif ($p == 'value') {
			$this->setValue($v);
		}
		else {
			$this->$p = $v;
		}
	}
	
	public function __get($p) {
		if ($p == 'selectedIndex') {
			return $this->_selectedIndex;
		}
		if ($p == 'value') {
			return $this->getValue();
		}		
		return $this->$p;
	}
	
	public function getValue() {
		foreach ($this as $option) {
			if ($option->selected) {
				return $option->value;
			}
		}
		return null;
	}
	
	public function setValue($v) {
		$setAlready = false;
		foreach ($this as $option) {
			if ($setAlready == false && $option->value == $v) {
				$option->selected = true;
				$setAlready = true;
			}
			else {
				$option->selected = false;
			}
		}
		return $this;
	}
	
	public function invoke($m,$a) {
		$results = array();
		foreach ($this as $option) {
			$results[] = call_user_func_array(array($option, $m), $a);
		}
		return $results;
	}
	
	public function __toString() {
		$html = '';
		foreach ($this as $i => $option) {
			$html .= (string) $option;
			//$html .= '<option value="' . $i . '">option ' . $i . '</option>';
		}
		return $html;
	}
	
}

